package ddbs;

import java.io.IOException;
import java.net.InetSocketAddress;

import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpServer;

public class Gui implements JobDoneCallback {
    Sched sch = null;
    int port;

    public Gui(Configuration conf, Sched sch, int port) {
        this.sch = sch;
        if (port <= 0)
            port = 8888;
        this.port = port;
    }

    private void startHttpServer() {
        try {
            HttpServer hs = HttpServer.create(new InetSocketAddress(
                    "localhost", port), 10);
            HttpContext context = hs.createContext("/",
                    new SQLHttpHandler(this));
            hs.setExecutor(null);
            context.getFilters().add(new ParameterFilter());
            System.out.println("Http server listen on " + port);
            hs.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void jobdonecb(Object obj) {
        Workload wkload = (Workload) obj;
        sch.finishWorkload(wkload);
        synchronized (wkload) {
            wkload.notify();
        }
    }

    public Data handleSQL(String sql) {
        Workload wkload = new Workload(sch.getMgr(), sql);
        wkload.show();
        wkload.donecb = this;
        sch.dealwithWorkload(wkload);
        if (wkload.is_done) {
            return wkload.data;
        } else {
            try {
                synchronized (wkload) {
                    wkload.wait();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return wkload.data;
        }
    }

    public Data handleSQL2(String sql) {
        System.out.println("handleSQL:" + sql);
        return DatabaseQuery.query(sql);
    }

    void start() {
        startHttpServer();
    }
}
